package calculator;

import java.util.Comparator;

import bean.Card;

/**
 * scoring system: higher score = more likely to play the card <br>
 * stable comparator
 * 
 * @author lchongsh
 * 
 */
public class CardComparator implements Comparator<Card> {

	private Card indexCard;
	private int trump;
	private boolean surrender;

	@Override
	public int compare(Card o1, Card o2) {
		if (o1.equals(o2))
			return 0;

		if (surrender) {
			int o1score = (13 - o1.getRank()) * 4 + o1.getSuit() + (trump == o1.getSuit() ? -100 : 0);
			int o2score = (13 - o2.getRank()) * 4 + o2.getSuit() + (trump == o2.getSuit() ? -100 : 0);
			return o1score < o2score ? 1 : -1;
		}
		// null = first to play a card, draw trump first
		if (indexCard == null) {
			int o1score = (13 - o1.getRank()) * 4 + o1.getSuit() + (trump == o1.getSuit() ? 100 : 0);
			int o2score = (13 - o2.getRank()) * 4 + o2.getSuit() + (trump == o2.getSuit() ? 100 : 0);
			return o1score < o2score ? 1 : -1;
		}

		// try to win the trick with minimum card
		if (indexCard.getSuit() == trump) {
			int o1score = (13 - o1.getRank()) * 4 + o1.getSuit();
			int o2score = (13 - o2.getRank()) * 4 + o2.getSuit();
			if (o1.getSuit() != trump)
				;
			else if (o1.getSuit() == trump && o1.getRank() > indexCard.getRank())
				o1score += 100;
			else
				o1score -= 100;
			if (o2.getSuit() != trump)
				;
			else if (o2.getSuit() == trump && o2.getRank() > indexCard.getRank())
				o2score += 100;
			else
				o2score -= 100;
			return o1score < o2score ? 1 : -1;
		} else {
			int o1score = (13 - o1.getRank()) * 4 + o1.getSuit() + (trump == o1.getSuit() ? 200 : 0);
			if (indexCard.getSuit() == o1.getSuit() && indexCard.getRank() < o1.getRank())
				o1score += 100;
			int o2score = (13 - o2.getRank()) * 4 + o2.getSuit() + (trump == o2.getSuit() ? 200 : 0);
			if (indexCard.getSuit() == o2.getSuit() && indexCard.getRank() < o2.getRank())
				o2score += 100;
			return o1score < o2score ? 1 : -1;

		}
	}

	public Card getIndexCard() {
		return indexCard;
	}

	public void setIndexCard(Card indexCard) {
		this.indexCard = indexCard;
	}

	public int getTrump() {
		return trump;
	}

	public void setTrump(int trump) {
		this.trump = trump;
	}

	public boolean getSurrender() {
		return surrender;
	}

	public void setSurrender(boolean surrender) {
		this.surrender = surrender;
	}
}
